package at.fhj.swd.pse.beans;

import java.util.Date;
import java.util.List;

import javax.enterprise.inject.Model;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;


import at.fhj.swd.pse.domain.ActivityService;
import at.fhj.swd.pse.entities.Activity;
import at.fhj.swd.pse.entities.EActivityType;

@Model
public class ActivityBean {

	@Inject
	private LoginBean lb;

	@Inject
	private CommunityBean cb;
	
	@Inject
	private ActivityService as;

	@Named
	public Boolean isLoggedIn() {
		return this.lb.isLoggedIn();
	}

	private String newActivityText;

	public String getNewActivityText() {
		return this.newActivityText;
	}

	public void setNewActivityText(final String newActivityText) {
		this.newActivityText = newActivityText;
	}

	@Named
	public void newActivtiy() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		if (this.lb.isLoggedIn() && (this.newActivityText != null)) {
			Activity activity = new Activity();
			activity.setCreator(this.lb.getLoggedInUser());
			activity.setText(this.newActivityText);
			activity.setTimestamp(new Date(System.currentTimeMillis()));
									
			if(cb.getCurrentCommunity() != null) {
				activity.setType(EActivityType.Community);
				this.as.createNewActivity(activity, cb.getCurrentCommunity());
			}
			else {
				activity.setType(EActivityType.Friend);
				this.as.createNewActivity(activity);
			}
					
			this.newActivityText = "";
			FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message successfull created!", "Message successfull created!");
			facesContext.addMessage(null, m);
		}
	}
	
	@Named
	public String newCommunityActivity()
	{
		newActivtiy();
		return "communitydetails?id=" + cb.getCurrentCommunity().getID() + "&faces-redirect=true";	
	}

	public List<Activity> getActivities() {
		return this.as.getAllActivities(this.lb.getLoggedInUser().getId());
	}

	@Named
	public void removeActivity(final Activity activity) {
		this.newActivityText = "";
		FacesContext facesContext = FacesContext.getCurrentInstance();
		FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_INFO, "Message successfull deleted!", "Message successfull deleted!");
		facesContext.addMessage(null, m);

		this.as.removeActivity(activity);
	}

	@Named
	public boolean isDeleteable(final Activity activity) {
		if (activity.getCreator().equals(this.lb.getLoggedInUser()) && (activity.getType() == EActivityType.Friend)) {
			return true;
		}
		return false;
	}
}
